package br.nextfm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.nextfm.dao.AlbumDao;
import br.nextfm.dao.CategoriaDao;
import br.nextfm.dao.MusicaDao;
import br.nextfm.model.Album;
import br.nextfm.model.Categoria;
import br.nextfm.model.Musica;

public class AtualizaMusica extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int id = Integer.parseInt(request.getParameter("id"));
		
		MusicaDao dao = new MusicaDao();
		AlbumDao albumDao = new AlbumDao();
		CategoriaDao categoriaDao = new CategoriaDao();
		Musica musica = dao.get(id);
		
		request.setAttribute("musicaSelecionada", musica);
		request.setAttribute("editar", true);
		request.setAttribute("categorias", categoriaDao.getAll());
		request.setAttribute("albums", albumDao.getAll());
		request.setAttribute("musicas", dao.getAll());
		request.getRequestDispatcher("musica.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String nome = request.getParameter("nome");
		String tags = request.getParameter("tags");
		String diretorio = request.getParameter("diretorio");
		
		int idCategoria = Integer.parseInt(request.getParameter("categoria"));
		int idAlbum = Integer.parseInt(request.getParameter("album"));
		int id = Integer.parseInt(request.getParameter("id"));
		
		
		AlbumDao albumDao = new AlbumDao();
		CategoriaDao categoriaDao = new CategoriaDao();
		MusicaDao musicaDao = new MusicaDao();
		
		Album album = albumDao.get(idAlbum);
		Categoria categoria = categoriaDao.get(idCategoria);
		Musica musica = musicaDao.get(id);
		
		musica.setAlbum(album);
		musica.setCategoria(categoria);
		musica.setDiretorio(diretorio);
		musica.setNome(nome);
		musica.setTags(tags);

		if (!categoria.getMusicas().contains(musica)) {
			categoria.getMusicas().add(musica);
		}
		if (!album.getMusicas().contains(musica)) {
			album.getMusicas().add(musica);
		}
		
		if (musicaDao.update(musica)) {
			
			albumDao.update(album);
			categoriaDao.update(categoria);
			
		}
		
		request.setAttribute("musicas", musicaDao.getAll());
		request.setAttribute("albums", albumDao.getAll());
		request.setAttribute("categorias", categoriaDao.getAll());
		request.getRequestDispatcher("musica.jsp").forward(request, response);
		
	}

}
